<template>
  <div class="profile-page">
    <!-- 页面头部 -->
    <header class="page-header">
      <div class="header-container">
        <div class="logo-section">
          <h1 class="store-title">
            <span class="leaf-icon"><i class="fas fa-user-cog"></i></span>
            个人设置
          </h1>
        </div>
      </div>
    </header>

    <div class="profile-container">
      <!-- 侧边栏菜单 -->
      <div class="profile-sidebar">
        <div class="user-card">
          <div class="user-avatar">
            <img :src="userInfo.avatar" alt="用户头像" class="avatar-image" />
            <div class="avatar-upload" @click="showAvatarUpload = true">
              <span class="upload-icon">📷</span>
            </div>
          </div>
          <div class="user-info">
            <h3 class="user-name">{{ userInfo.nickname }}</h3>
            <p class="user-phone">{{ userInfo.phone }}</p>
            <p class="user-level">买家</p>
          </div>
        </div>

        <div class="sidebar-menu">
          <div
            v-for="item in menuItems"
            :key="item.key"
            :class="['menu-item', { active: activeMenu === item.key }]"
            @click="activeMenu = item.key"
          >
            <span class="menu-icon">{{ item.icon }}</span>
            <span class="menu-text">{{ item.text }}</span>
          </div>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="profile-content">
        <!-- 基本信息 -->
        <div v-if="activeMenu === 'basic'" class="content-section">
          <h2 class="section-title">基本信息</h2>
          <el-form :model="userInfo" :rules="formRules" ref="basicForm" label-width="100px">
            <el-form-item label="头像">
              <div class="avatar-upload-section">
                <img :src="userInfo.avatar" alt="用户头像" class="current-avatar" />
                <el-button type="primary" @click="showAvatarUpload = true">更换头像</el-button>
              </div>
            </el-form-item>

            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="userInfo.nickname" placeholder="请输入昵称" />
            </el-form-item>

            <el-form-item label="手机号" prop="phone" aria-disabled="false">
              <el-input v-model="userInfo.phone" placeholder="请输入手机号" disabled />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userInfo.email" placeholder="请输入邮箱地址" disabled />
            </el-form-item>

            <el-form-item label="性别">
              <el-radio-group v-model="userInfo.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
                <el-radio :label="0">保密</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="生日">
              <el-date-picker
                v-model="userInfo.birthday"
                type="date"
                placeholder="选择生日"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveBasicInfo">保存修改</el-button>
              <el-button @click="resetBasicInfo">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 安全设置 -->
        <div v-else-if="activeMenu === 'security'" class="content-section">
          <h2 class="section-title">安全设置</h2>
          <div class="security-items">
            <div class="security-item">
              <div class="item-info">
                <h4 class="item-title">登录密码</h4>
                <p class="item-desc">定期更换密码可以让账户更安全</p>
              </div>
              <el-button @click="showPasswordDialog = true">修改</el-button>
            </div>

            <div class="security-item">
              <div class="item-info">
                <h4 class="item-title">手机验证</h4>
                <p class="item-desc">已绑定手机：{{ userInfo.phone }}</p>
              </div>
              <el-button @click="showPhoneDialog = true">更换手机</el-button>
            </div>

            <div class="security-item">
              <div class="item-info">
                <h4 class="item-title">邮箱验证</h4>
                <p class="item-desc" :class="{ 'not-set': !userInfo.email }">
                  {{ userInfo.email || '未绑定邮箱' }}
                </p>
              </div>
              <el-button @click="showEmailDialog = true">
                {{ userInfo.email ? '更换邮箱' : '绑定邮箱' }}
              </el-button>
            </div>

            <div class="security-item">
              <div class="item-info">
                <h4 class="item-title">登录设备管理</h4>
                <p class="item-desc">管理您的登录设备</p>
              </div>
              <el-button @click="showDeviceManager = true">管理</el-button>
            </div>
          </div>
        </div>

        <!-- 隐私设置 -->
        <div v-else-if="activeMenu === 'privacy'" class="content-section">
          <h2 class="section-title">隐私设置</h2>
          
          <!-- 个人资料隐私 -->
          <div class="privacy-section">
            <div class="section-header">
              <h3 class="section-title">个人资料隐私</h3>
            </div>
            
            <div class="privacy-item">
              <div class="item-content">
                <div class="item-icon">
                  <span class="icon">👤</span>
                </div>
                <div class="item-info">
                  <h4 class="item-title">个人资料可见性</h4>
                  <p class="item-desc">控制其他用户可以看到您的哪些信息</p>
                </div>
                <el-select v-model="privacySettings.profileVisibility" placeholder="选择可见范围">
                  <el-option label="公开" value="public" />
                  <el-option label="仅好友" value="friends" />
                  <el-option label="仅自己" value="private" />
                </el-select>
              </div>
            </div>

            <div class="privacy-item">
              <div class="item-content">
                <div class="item-icon">
                  <span class="icon">📝</span>
                </div>
                <div class="item-info">
                  <h4 class="item-title">帖子可见性</h4>
                  <p class="item-desc">控制您发布的帖子的可见范围</p>
                </div>
                <el-select v-model="privacySettings.postVisibility" placeholder="选择可见范围">
                  <el-option label="公开" value="public" />
                  <el-option label="仅好友" value="friends" />
                  <el-option label="仅自己" value="private" />
                </el-select>
              </div>
            </div>

            <div class="privacy-item">
              <div class="item-content">
                <div class="item-icon">
                  <span class="icon">🟢</span>
                </div>
                <div class="item-info">
                  <h4 class="item-title">在线状态显示</h4>
                  <p class="item-desc">是否向其他用户显示您的在线状态</p>
                </div>
                <el-switch 
                  v-model="privacySettings.showOnlineStatus" 
                  active-text="显示" 
                  inactive-text="隐藏"
                />
              </div>
            </div>
          </div>

          <!-- 社交互动隐私 -->
          <div class="privacy-section">
            <div class="section-header">
              <h3 class="section-title">社交互动隐私</h3>
            </div>
            
            <div class="privacy-item">
              <div class="item-content">
                <div class="item-icon">
                  <span class="icon">✉️</span>
                </div>
                <div class="item-info">
                  <h4 class="item-title">私信接收</h4>
                  <p class="item-desc">控制谁可以向您发送私信</p>
                </div>
                <el-select v-model="privacySettings.privateMessage" placeholder="选择接收范围">
                  <el-option label="所有人" value="everyone" />
                  <el-option label="仅好友" value="friends" />
                  <el-option label="仅自己" value="none" />
                </el-select>
              </div>
            </div>

            <div class="privacy-item">
              <div class="item-content">
                <div class="item-icon">
                  <span class="icon">🔍</span>
                </div>
                <div class="item-info">
                  <h4 class="item-title">搜索可见性</h4>
                  <p class="item-desc">是否允许其他用户通过搜索找到您</p>
                </div>
                <el-switch 
                  v-model="privacySettings.searchable" 
                  active-text="允许" 
                  inactive-text="禁止"
                />
              </div>
            </div>
          </div>

          <div class="save-preferences">
            <el-button type="primary" @click="savePrivacySettings">保存设置</el-button>
          </div>
        </div>

        <!-- 收货地址 -->
        <div v-else-if="activeMenu === 'address'" class="content-section">
          <h2 class="section-title">
            收货地址
            <el-button type="primary" @click="addNewAddress" class="add-address-btn">
              + 添加新地址
            </el-button>
          </h2>
          
          <div class="address-list">
            <div
              v-for="address in userAddresses"
              :key="address.id"
              :class="['address-card', { default: address.isDefault }]"
            >
              <div class="address-content">
                <div class="address-header">
                  <span class="recipient">{{ address.recipient }}</span>
                  <span class="phone">{{ address.phone }}</span>
                  <span v-if="address.isDefault" class="default-badge">默认</span>
                  <span class="tag-badge" :class="getTagClass(address.tag)">
                    {{ address.tag }}
                  </span>
                </div>
                <div class="address-detail">
                  {{ address.province }} {{ address.city }} {{ address.district }} {{ address.detail }}
                </div>
              </div>
              <div class="address-actions">
                <el-button type="text" @click="setDefaultAddress(address.id)">设默认</el-button>
                <el-button type="text" @click="editAddress(address)">编辑</el-button>
                <el-button type="text" @click="deleteAddress(address.id)" class="delete-btn">删除</el-button>
              </div>
            </div>

            <div v-if="userAddresses.length === 0" class="empty-address">
              <div class="empty-icon">🏠</div>
              <p class="empty-text">暂无收货地址</p>
              <el-button type="primary" @click="addNewAddress">添加地址</el-button>
            </div>
          </div>
        </div>

        <!-- 账户偏好 -->
        <div v-else-if="activeMenu === 'preference'" class="content-section">
          <h2 class="section-title">账户偏好</h2>
          <div class="preference-items">
            <div class="preference-item">
              <div class="item-info">
                <h4 class="item-title">消息通知</h4>
                <p class="item-desc">订单状态、促销活动等消息通知</p>
              </div>
              <el-switch v-model="preferences.notifications" />
            </div>

            <div class="preference-item">
              <div class="item-info">
                <h4 class="item-title">邮件订阅</h4>
                <p class="item-desc">接收产品更新和优惠信息</p>
              </div>
              <el-switch v-model="preferences.emailSubscription" />
            </div>

            <div class="preference-item">
              <div class="item-info">
                <h4 class="item-title">短信提醒</h4>
                <p class="item-desc">订单状态短信提醒</p>
              </div>
              <el-switch v-model="preferences.smsReminder" />
            </div>

            <div class="preference-item">
              <div class="item-info">
                <h4 class="item-title">个性化推荐</h4>
                <p class="item-desc">根据您的喜好推荐商品</p>
              </div>
              <el-switch v-model="preferences.personalizedRecommendation" />
            </div>

            <div class="preference-item">
              <div class="item-info">
                <h4 class="item-title">主题设置</h4>
                <p class="item-desc">选择您喜欢的界面主题</p>
              </div>
              <el-radio-group v-model="preferences.theme">
                <el-radio label="light">浅色</el-radio>
                <el-radio label="dark">深色</el-radio>
                <el-radio label="auto">跟随系统</el-radio>
              </el-radio-group>
            </div>

            <div class="save-preferences">
              <el-button type="primary" @click="savePreferences">保存设置</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <el-dialog
      v-model="showAvatarUpload"
      title="更换头像"
      width="400px"
    >
      <div class="avatar-upload-dialog">
        <div class="avatar-preview">
          <img :src="avatarPreview" alt="头像预览" class="preview-image" />
        </div>
        <div class="upload-actions">
          <el-upload
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            accept="image/*"
          >
            <el-button type="primary">选择图片</el-button>
          </el-upload>
          <el-button @click="cropAvatar">裁剪图片</el-button>
        </div>
        <div class="upload-tips">
          <p>建议尺寸：200×200像素</p>
          <p>支持 JPG、PNG 格式，文件大小不超过 2MB</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="showAvatarUpload = false">取消</el-button>
        <el-button type="primary" @click="confirmAvatar">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="修改密码"
      width="400px"
    >
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="80px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="updatePassword">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改手机对话框 -->
    <el-dialog
      v-model="showPhoneDialog"
      title="更换手机号"
      width="400px"
    >
      <el-form :model="phoneForm" :rules="phoneRules" ref="phoneFormRef" label-width="80px">
        <el-form-item label="新手机号" prop="phone">
          <el-input v-model="phoneForm.phone" placeholder="请输入新手机号" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div class="code-input">
            <el-input v-model="phoneForm.code" placeholder="请输入验证码" />
            <el-button type="primary" :disabled="codeCountdown > 0" @click="sendCode">
              {{ codeCountdown > 0 ? `${codeCountdown}秒后重发` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPhoneDialog = false">取消</el-button>
        <el-button type="primary" @click="updatePhone">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改邮箱对话框 -->
    <el-dialog
      v-model="showEmailDialog"
      title="绑定邮箱"
      width="400px"
    >
      <el-form :model="emailForm" :rules="emailRules" ref="emailFormRef" label-width="80px">
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="emailForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div class="code-input">
            <el-input v-model="emailForm.code" placeholder="请输入验证码" />
            <el-button type="primary" :disabled="emailCodeCountdown > 0" @click="sendEmailCode">
              {{ emailCodeCountdown > 0 ? `${emailCodeCountdown}秒后重发` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEmailDialog = false">取消</el-button>
        <el-button type="primary" @click="updateEmail">确定</el-button>
      </template>
    </el-dialog>

    <!-- 地址编辑对话框 -->
    <el-dialog
      v-model="showAddressEdit"
      :title="editingAddress ? '编辑地址' : '添加地址'"
      width="500px"
    >
      <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef" label-width="80px">
        <el-form-item label="收货人" prop="recipient">
          <el-input v-model="addressForm.recipient" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <!-- 在地址编辑对话框中添加标签选择 -->
        <el-form-item label="地址标签">
          <div class="tag-selector">
            <el-radio-group v-model="addressForm.tag">
              <el-radio 
                v-for="tag in addressTags" 
                :key="tag" 
                :label="tag"
                class="tag-radio"
              >
                {{ tag }}
              </el-radio>
            </el-radio-group>
            <el-input
              v-if="addressForm.tag === '其他'"
              v-model="addressForm.customTag"
              placeholder="请输入自定义标签"
              style="margin-top: 8px; width: 200px;"
            />
          </div>
        </el-form-item>

        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"
            placeholder="请选择所在地区"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input
            v-model="addressForm.detail"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddressEdit = false">取消</el-button>
        <el-button type="primary" @click="saveAddress">保存</el-button>
      </template>
    </el-dialog>

    <!-- 登录设备管理 -->
    <el-dialog
      v-model="showDeviceManager"
      title="登录设备管理"
      width="600px"
    >
      <div class="device-manager">
        <div class="device-list">
          <div
            v-for="device in loginDevices"
            :key="device.id"
            class="device-item"
          >
            <div class="device-info">
              <div class="device-header">
                <span class="device-name">{{ device.deviceName }}</span>
                <span v-if="device.isCurrent" class="current-badge">当前设备</span>
              </div>
              <div class="device-detail">
                <span>{{ device.location }}</span>
                <span>最后登录：{{ device.lastLogin }}</span>
              </div>
            </div>
            <div class="device-actions">
              <el-button
                type="text"
                @click="logoutDevice(device.id)"
                :disabled="device.isCurrent"
              >
                退出登录
              </el-button>
            </div>
          </div>
        </div>
        <div class="device-actions-footer">
          <el-button @click="logoutAllDevices">退出所有设备</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { regionOptions } from '@/utils/regionData'

const router = useRouter()

const addressFormRef = ref(null)

// 菜单项
const menuItems = ref([
  { key: 'basic', text: '基本信息', icon: '👤' },
  { key: 'security', text: '安全设置', icon: '🔒' },
  { key: 'privacy', text: '隐私设置', icon: ' 👀' },
  { key: 'address', text: '收货地址', icon: '🏠' },
  { key: 'preference', text: '账户偏好', icon: '⚙️' }
])

const activeMenu = ref('basic')

// 预设标签选项
const addressTags = ref(['家', '公司', '学校', '父母家', '其他'])

// 用户信息
const userInfo = ref({
  avatar: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=200&h=200&fit=crop&crop=face',
  nickname: '有机生活爱好者',
  phone: '13800138000',
  email: 'user@example.com',
  gender: 1,
  birthday: '1990-01-01'
})

// 收货地址
const userAddresses = ref([
  {
    id: 1,
    recipient: '张三',
    phone: '13800138000',
    province: '北京市',
    city: '北京市',
    district: '朝阳区',
    detail: '建国路88号SOHO现代城A座1001室',
    isDefault: true,
    tag: '家'
  },
  {
    id: 2,
    recipient: '李四',
    phone: '13900139000',
    province: '上海市',
    city: '上海市',
    district: '浦东新区',
    detail: '陆家嘴环路1000号汇亚大厦',
    isDefault: false,
    tag: '公司'
  }
])

// 账户偏好
const preferences = ref({
  notifications: true,
  emailSubscription: true,
  smsReminder: true,
  personalizedRecommendation: true,
  theme: 'light'
})

// 登录设备
const loginDevices = ref([
  {
    id: 1,
    deviceName: 'iPhone 13 Pro',
    location: '北京',
    lastLogin: '2024-12-01 10:30:00',
    isCurrent: true
  },
  {
    id: 2,
    deviceName: 'MacBook Pro',
    location: '上海',
    lastLogin: '2024-11-28 14:20:00',
    isCurrent: false
  }
])

// 对话框控制
const showAvatarUpload = ref(false)
const showPasswordDialog = ref(false)
const showPhoneDialog = ref(false)
const showEmailDialog = ref(false)
const showAddressEdit = ref(false)
const showDeviceManager = ref(false)

// 表单数据
const avatarPreview = ref(userInfo.value.avatar)
const editingAddress = ref(null)

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const phoneForm = ref({
  phone: '',
  code: ''
})

const emailForm = ref({
  email: '',
  code: ''
})

const addressForm = ref({
  recipient: '',
  phone: '',
  region: [],
  detail: '',
  isDefault: false,
  tag: '家', // 默认标签
  customTag: '' // 自定义标签
})

// 倒计时
const codeCountdown = ref(0)
const emailCodeCountdown = ref(0)

// 表单验证规则
const formRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为6位', trigger: 'blur' }
  ]
}

const emailRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

const addressRules = {
  recipient: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  tag: [
    { required: true, message: '请选择地址标签', trigger: 'change' }
  ]
}

//隐私设置
const privacySettings = ref({
  profileVisibility: 'public',
  postVisibility: 'public',
  showOnlineStatus: true,
  privateMessage: 'everyone',
  searchable: true
})

// 保存隐私设置的方法
const savePrivacySettings = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('隐私设置已保存')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 方法
const saveBasicInfo = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('基本信息更新成功')
  } catch (error) {
    ElMessage.error('更新失败，请重试')
  }
}

const resetBasicInfo = () => {
  userInfo.value = {
    avatar: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=200&h=200&fit=crop&crop=face',
    nickname: '有机生活爱好者',
    phone: '13800138000',
    email: 'user@example.com',
    gender: 1,
    birthday: '1990-01-01'
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  // 创建预览
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    avatarPreview.value = reader.result
  }
  return false // 阻止自动上传
}

const cropAvatar = () => {
  ElMessage.info('打开图片裁剪功能')
  // 这里可以集成图片裁剪库
}

const confirmAvatar = () => {
  userInfo.value.avatar = avatarPreview.value
  showAvatarUpload.value = false
  ElMessage.success('头像更新成功')
}

const updatePassword = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    showPasswordDialog.value = false
    passwordForm.value = { oldPassword: '', newPassword: '', confirmPassword: '' }
    ElMessage.success('密码修改成功')
  } catch (error) {
    ElMessage.error('密码修改失败')
  }
}

const sendCode = () => {
  codeCountdown.value = 60
  const timer = setInterval(() => {
    codeCountdown.value--
    if (codeCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
  ElMessage.success('验证码已发送')
}

const sendEmailCode = () => {
  emailCodeCountdown.value = 60
  const timer = setInterval(() => {
    emailCodeCountdown.value--
    if (emailCodeCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
  ElMessage.success('验证码已发送到邮箱')
}

const updatePhone = async () => {
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    userInfo.value.phone = phoneForm.value.phone
    showPhoneDialog.value = false
    phoneForm.value = { phone: '', code: '' }
    ElMessage.success('手机号更新成功')
  } catch (error) {
    ElMessage.error('手机号更新失败')
  }
}

const updateEmail = async () => {
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    userInfo.value.email = emailForm.value.email
    showEmailDialog.value = false
    emailForm.value = { email: '', code: '' }
    ElMessage.success('邮箱绑定成功')
  } catch (error) {
    ElMessage.error('邮箱绑定失败')
  }
}

const savePreferences = async () => {
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('偏好设置已保存')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 地址管理方法
const addNewAddress = () => {
  editingAddress.value = null
  addressForm.value = {
    recipient: '',
    phone: '',
    region: [],
    detail: '',
    isDefault: false,
    tag: '家', // 设置默认标签
    customTag: '' // 初始化自定义标签字段
  }
  showAddressEdit.value = true
}

const editAddress = (address) => {
  editingAddress.value = address
  addressForm.value = {
    recipient: address.recipient,
    phone: address.phone,
    region: [address.province, address.city, address.district],
    detail: address.detail,
    isDefault: address.isDefault,
    tag: address.tag,
    customTag: address.tag && !addressTags.value.includes(address.tag) ? address.tag : ''
  }
  showAddressEdit.value = true
}

const saveAddress = async () => {
  try {
    await addressFormRef.value.validate()
    
    if (addressForm.value.region.length !== 3) {
      ElMessage.error('请选择完整的省市区')
      return
    }
    
    const [province, city, district] = addressForm.value.region
    const finalTag = addressForm.value.tag === '其他' && addressForm.value.customTag 
      ? addressForm.value.customTag 
      : addressForm.value.tag
    
    // 如果是自定义标签且不在标签列表中，添加到标签列表
    if (addressForm.value.tag === '其他' && addressForm.value.customTag && 
        !addressTags.value.includes(addressForm.value.customTag)) {
      addressTags.value.push(addressForm.value.customTag)
    }
    
    if (editingAddress.value) {
      // 更新地址
      const index = userAddresses.value.findIndex(addr => addr.id === editingAddress.value.id)
      if (index !== -1) {
        userAddresses.value[index] = {
          ...userAddresses.value[index],
          recipient: addressForm.value.recipient,
          phone: addressForm.value.phone,
          province,
          city,
          district,
          detail: addressForm.value.detail,
          isDefault: addressForm.value.isDefault,
          tag: finalTag
        }
      }
    } else {
      // 新增地址
      const newAddress = {
        id: Date.now(),
        recipient: addressForm.value.recipient,
        phone: addressForm.value.phone,
        province,
        city,
        district,
        detail: addressForm.value.detail,
        isDefault: addressForm.value.isDefault,
        tag: finalTag
      }
      userAddresses.value.push(newAddress)
    }
    
    // 处理默认地址
    if (addressForm.value.isDefault) {
      userAddresses.value.forEach(addr => {
        if (addr.id !== (editingAddress.value?.id || Date.now())) {
          addr.isDefault = false
        }
      })
    }
    
    showAddressEdit.value = false
    ElMessage.success(editingAddress.value ? '地址更新成功' : '地址添加成功')
  } catch (error) {
    console.error('保存地址错误:', error)
    ElMessage.error('请完善地址信息')
  }
}


const setDefaultAddress = (addressId) => {
  userAddresses.value.forEach(addr => {
    addr.isDefault = addr.id === addressId
  })
  ElMessage.success('默认地址设置成功')
}

const deleteAddress = (addressId) => {
  ElMessageBox.confirm('确定要删除这个地址吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userAddresses.value = userAddresses.value.filter(addr => addr.id !== addressId)
    ElMessage.success('地址删除成功')
  })
}

// 设备管理方法
const logoutDevice = (deviceId) => {
  ElMessageBox.confirm('确定要让这个设备退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    loginDevices.value = loginDevices.value.filter(device => device.id !== deviceId)
    ElMessage.success('设备已退出登录')
  })
}

const logoutAllDevices = () => {
  ElMessageBox.confirm('确定要让所有设备退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loginDevices.value = loginDevices.value.filter(device => device.isCurrent)
    ElMessage.success('其他设备已全部退出登录')
  })
}

// 添加标签样式方法
const getTagClass = (tag) => {
  const tagClasses = {
    '家': 'tag-home',
    '公司': 'tag-company',
    '学校': 'tag-school',
    '父母家': 'tag-parents',
    '其他': 'tag-other'
  }
  return tagClasses[tag] || 'tag-other'
}

onMounted(() => {
  // 可以在这里加载用户数据
})
</script>

<style scoped>
/* 标签徽章样式 */
.tag-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: white;
  margin-left: 8px;
}

.tag-home {
  background: #10b981;
}

.tag-company {
  background: #3b82f6;
}

.tag-school {
  background: #f59e0b;
}

.tag-parents {
  background: #8b5cf6;
}

.tag-other {
  background: #6b7280;
}

/* 标签选择器样式 */
.tag-selector {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tag-radio {
  margin-right: 16px;
}

/* 空地址样式调整 */
.empty-address {
  text-align: center;
  padding: 60px 20px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.3;
}

.empty-text {
  color: #6b7280;
  margin-bottom: 20px;
}

.profile-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.page-header {
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px 0;
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.store-title {
  color: #10b981;
  font-size: 24px;
  font-weight: 700;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.leaf-icon {
  font-size: 20px;
}

.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 30px;
}

/* 侧边栏样式 */
.profile-sidebar {
  position: sticky;
  top: 30px;
  height: fit-content;
}

.user-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 20px;
}

.user-avatar {
  position: relative;
  display: inline-block;
  margin-bottom: 16px;
}

.avatar-image {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-upload {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background: #10b981;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: 2px solid white;
}

.upload-icon {
  color: white;
  font-size: 14px;
}

.user-name {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.user-phone {
  color: #6b7280;
  margin: 0 0 8px 0;
}

.user-level {
  color: #10b981;
  font-weight: 500;
  margin: 0;
}

.sidebar-menu {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
}

.menu-item:hover {
  background: #f8fafc;
  color: #10b981;
}

.menu-item.active {
  background: #f0fdf4;
  color: #10b981;
  border-left-color: #10b981;
}

.menu-icon {
  font-size: 18px;
}

.menu-text {
  font-weight: 500;
}

/* 内容区域样式 */
.profile-content {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-address-btn {
  font-size: 14px;
}

/* 基本信息样式 */
.avatar-upload-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.current-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

/* 安全设置样式 */
.security-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.item-info {
  flex: 1;
}

.item-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 4px 0;
}

.item-desc {
  color: #6b7280;
  margin: 0;
}

.item-desc.not-set {
  color: #ef4444;
}

/* 隐私设置样式 */
.privacy-section {
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e7eb;
}

.section-header .icon {
  font-size: 16px;
  color: #10b981;
}

.privacy-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  margin-bottom: 16px;
}

.item-content {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

.item-icon {
  width: 40px;
  height: 40px;
  background: #f0fdf4;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.item-icon .icon {
  font-size: 18px;
  color: #10b981;
}

.item-info {
  flex: 1;
}

.item-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 4px 0;
}

.item-desc {
  color: #6b7280;
  font-size: 14px;
  margin: 0;
}

.el-select {
  width: 120px;
}

.el-switch {
  margin-left: 16px;
}

/* 地址管理样式 */
.address-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.address-card {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.address-card.default {
  border-color: #10b981;
  background: #f0fdf4;
}

.address-content {
  flex: 1;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.recipient {
  font-weight: 600;
  color: #1f2937;
}

.phone {
  color: #6b7280;
}

.default-badge {
  background: #10b981;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.address-detail {
  color: #6b7280;
  line-height: 1.4;
}

.address-actions {
  display: flex;
  gap: 8px;
}

.delete-btn {
  color: #ef4444;
}

.empty-address {
  text-align: center;
  padding: 60px 20px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.3;
}

.empty-text {
  color: #6b7280;
  margin-bottom: 20px;
}

/* 偏好设置样式 */
.preference-items {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.preference-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.save-preferences {
  text-align: center;
  margin-top: 30px;
}

/* 头像上传对话框 */
.avatar-upload-dialog {
  text-align: center;
}

.avatar-preview {
  margin-bottom: 20px;
}

.preview-image {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e5e7eb;
}

.upload-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-bottom: 16px;
}

.upload-tips {
  color: #6b7280;
  font-size: 14px;
}

.upload-tips p {
  margin: 4px 0;
}

/* 验证码输入样式 */
.code-input {
  display: flex;
  gap: 12px;
}

/* 设备管理样式 */
.device-manager {
  max-height: 400px;
  overflow-y: auto;
}

.device-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.device-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.device-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.device-name {
  font-weight: 600;
  color: #1f2937;
}

.current-badge {
  background: #10b981;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.device-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
  color: #6b7280;
  font-size: 14px;
}

.device-actions-footer {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .profile-sidebar {
    position: static;
  }
  
  .header-container {
    flex-direction: column;
    gap: 16px;
  }
  
  .security-item,
  .preference-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .address-card {
    flex-direction: column;
    gap: 12px;
  }
  
  .address-actions {
    align-self: flex-end;
  }
}
</style>